package group_01.MultiSnakeServer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Martin Nume
 * 	The WelcomeServer class is the initial connector between the serverprogram and the clients.
 */
public class WelcomeServer implements Runnable{
	//-----------------------
	//Constants
	//-----------------------
	private final int WELCOME_PORT;
	//-----------------------
	//Fields
	//-----------------------
	private ServerEngine serverEngine;
	private ServerSocket servSocket;
	private Thread thread;
	
	private Socket clientSocket;
	private BufferedReader in;
	private PrintWriter out;
	//-----------------------
	//Constructor
	//-----------------------
	public WelcomeServer(ServerEngine serverEngine, int welcomePort){
	WELCOME_PORT = welcomePort;
	out=null;
	this.serverEngine = serverEngine;
	thread = new Thread(this);
	thread.start();
	
	}
	//----------------------
	//Methods
	//----------------------
	/**
	 *Run() awaits incoming connections from clients, then read their command and execute it.
	 */
	@Override
	public void run() {
		
			try{
				servSocket = new ServerSocket(WELCOME_PORT);
			}
			catch(IOException aes){
				 System.out.println("Could not create server socket on" + WELCOME_PORT+ ". Quitting."); 
		            System.exit(-1); 
			}
			
			System.out.println("Listening for clients on port: " + WELCOME_PORT);
				
			String[] command ;
			 
				while(true) {
					in = null;
					clientSocket = null;
					try {
						try{ 
						
						clientSocket = servSocket.accept();
						
						//reads the command from the client
						 command = readCommand();
						 System.out.println("Command is: ");
						 for(int i =0; i<command.length; i++){
							 System.out.println(command[i]);
						 }
						}
						finally{
							//if(in != null)
								//in.close();
						}
					}
					catch(IOException e){
						 System.out.println("Could not read command from the client, discarding connection");
						 e.printStackTrace();
						 continue;
					}
						//an invalid command sent from the client. do nothing
						if(command.length <= 0)
							continue;
						
						//get list of Servers
						if(command[0].equals("GET_SERVERLIST")) {
							new ServerListHandler(this, clientSocket);
							System.out.println("Sending ServerList to client.. ");
						}
						// join  game
						else if(command[0].equals("JOIN_GAME")) {
							serverEngine.joinGame(command[1], command[2], clientSocket);
							
						}
						//host game then join it
						else if(command[0].equals("HOST_GAME")) {
							int maxPlayers = Integer.parseInt(command[2]);
							
							if(maxPlayers > 0){
								String gameId = serverEngine.AddGame(new GameHandler(command[1],maxPlayers));
								out.println("host_game;" + gameId+ ";" + command[1]+ ";1;" + maxPlayers);
								out.flush();
							}
						}
					
				}
			
	}
	
	/**
	 * Reads the command from the client
	 * @return command
	 * @throws IOException
	 */
	private String[] readCommand() throws IOException{
		in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
		return in.readLine().split(";");
	}

	/**
	 * Retrieves the list of servers from ServerEngine
	 * @return list of servers
	 */
	public String getServerList() {
		
		return serverEngine.GameListToString();
	}
	
}
